<script setup lang="ts">
import { getUserInfoById } from '@/api/user/user'
import { componentSizeMap, useFormSize } from 'element-plus'
import { computed, defineEmits, defineProps, onMounted, reactive, withDefaults } from 'vue'

export interface UserTagProps {
  user: object
  type?: 'success' | 'info' | 'warning' | 'danger'
  closable?: boolean
}

const $props = withDefaults(defineProps<UserTagProps>(), {
  user: undefined,
  closable: false,
  type: 'info'
})
const $emits = defineEmits<{
  (e: 'close', id: string): void
}>()

export interface UserInfo {
  id?: string
  username?: string
  avatar?: string
  realName?: string
}

let userInfo = reactive<UserInfo>({
  id: undefined,
  username: undefined,
  avatar: undefined,
  realName: undefined
})
onMounted(() => {
  if ($props.user) {
    userInfo.id = $props.user.id
    userInfo.username = $props.user.username
    userInfo.avatar = $props.user.avatar
    userInfo.realName = $props.user.realName
    // getUserInfoById($props.user.id).then((res) => {
    //   if (res.success) {
    //     userInfo.username = res.data.username
    //     userInfo.avatar = res.data.avatar
    //     userInfo.realName = res.data.realName
    //   }
    // })
  }
})
const formSize = useFormSize()
const getComponentSize = computed(() => {
  return componentSizeMap[formSize.value || 'default'] - 12
})
const firstChar = (name: string) => {
  if (!name) return ''; // 非空校验
  if (typeof name !== 'string') return ''; // 类型校验
  return name.charAt(0);
};
const onClose = () => {
  $emits('close', userInfo.id)
}
</script>
<template>
  <el-tag round :closable="$props.closable" :type="type" effect="light" @close="onClose">
    <div class="flex-center" style="gap: 4px; grid-gap: 4px">
      <el-avatar :size="getComponentSize" :src="userInfo.avatar">
        {{ firstChar(userInfo.realName) }}
      </el-avatar>
      <span class="ml-[5px]">{{ userInfo.realName }}</span>
    </div>
  </el-tag>
</template>

<style scoped lang="scss">
:deep {
  .el-tag__content:only-child {
    margin-right: 4px;
  }
}
</style>
